/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.lidovky.articles.reindexing;

import cz.mzk.lidovky.articles.PropertyNames;
import cz.mzk.rehan.commons.PropertyLoader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class Reindexer {

    private static final Logger logger = Logger.getLogger(Reindexer.class.getName());
    private static final String okResponse = "[reindex]PLANNED";
    private final String urlTemplate;

    public Reindexer(PropertyLoader properties) {
        urlTemplate = buildUrlTemplate(properties);
    }

    private String buildUrlTemplate(PropertyLoader loader) {
        String urlPrefix = loader.loadString(PropertyNames.KRAMERIUS_URL);
        String userName = loader.loadString(PropertyNames.KRAMERIUS_USER);
        String password = loader.loadString(PropertyNames.KRAMERIUS_PASSWORD);
        return urlPrefix + "/lr?action=start&def=reindex&out=text&params=fromKrameriusModel,%s,reindexing_%s_&userName=" + userName + "&pswd=" + password;
    }

    public void reindex(String uuid) throws Exception {
        logger.log(Level.INFO, "reindexing issue with uuid {0}", uuid);
        String url = String.format(urlTemplate, uuid, uuid);
        //System.out.println("url: '" + url + "'");
        String response = request(new URL(url));
        if (!okResponse.equals(response)) {
            throw new Exception("incorrect response '" + response + "' to request '" + url + "'");
        }
    }

    private String request(URL url) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder result = new StringBuilder();
        while (reader.ready()) {
            result.append(reader.readLine());
        }
        in.close();
        return result.toString();
    }
}
